<template>
    <div>
        <!--面包屑导航区-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片视图区域-->
        <el-card>
            <!--搜索与添加区域-->
            <!--:gutter: el-col的间距, :span栅格长度-->
            <el-row :gutter="20">
                <el-col :span="8">
                    <!--@clear: 清空搜索栏同时数据全部展示-->
                    <el-input placeholder="请输入内容" class="input-with-select"
                              v-model="queryInfo.query" clearable @clear="getUsers">
                        <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!--表格区域-->
            <el-table
                    :data="tableData"
                    width="100%"
                    border
                    stripe>
                <el-table-column type="index" width="50" label="#"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="roles" label="角色">
                    <template slot-scope="scope">
                        <el-tag type="primary" disable-transitions>{{scope.row.roles}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="80">
                    <!-- 可以使用作用域插槽获取当前列的数据, 从而获取我们的status-->
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.status" @change="changeStatus(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="showEdit(scope.row)"
                                   icon="el-icon-edit"></el-button>
                        <el-button type="danger" size="mini" @click="deleteUser(scope.row.id)"
                                   icon="el-icon-delete"></el-button>
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" size="mini" @click="showSetRole(scope.row)"
                                       icon="el-icon-setting"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!--分页区域-->
            <!--layout: 指定分页主键显示-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pageIndex"
                    :page-sizes="[5,10,20,50]"
                    :page-size="queryInfo.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>

        <!-- 添加用户对话框-->
        <el-dialog
                title="添加用户"
                :visible.sync="addDialogVisible"
                width="50%"
                @close="closeForm">
            <!-- 主体区域-->
            <el-form :model="form" ref="formRef" :rules="rules" status-icon>
                <el-form-item label="用户名" label-width="70px" prop="username">
                    <el-input v-model="form.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" label-width="70px" prop="password">
                    <el-input type="password" v-model="form.password" autocomplete="new-password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" label-width="70px" prop="email">
                    <el-input v-model="form.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" label-width="70px" prop="mobile">
                    <el-input v-model="form.mobile" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <!--按钮区域-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
              </span>
        </el-dialog>

        <!-- 修改用户对话框-->
        <el-dialog
                title="修改用户"
                :visible.sync="editDialogVisible"
                width="50%"
                @close="closeEditForm">
            <!-- 主体区域-->
            <el-form :model="editForm" ref="editFormRef" :rules="rules" status-icon>
                <el-form-item label="用户名" label-width="70px">
                    <el-input v-model="editForm.username" disabled autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" label-width="70px" prop="email">
                    <el-input v-model="editForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" label-width="70px" prop="mobile">
                    <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <!--按钮区域-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateUser">确 定</el-button>
              </span>
        </el-dialog>

        <!-- 分配角色对话框-->
        <el-dialog
                title="分配角色"
                :visible.sync="setRoleDialogVisible"
                width="50%"
                @close="closeSetRoleForm">
            <!-- 主体区域-->
            <div>
                <p>当前用户: {{userInfo.username}}</p>
                <p>当前角色: {{userInfo.roles}}</p>
                <p>分配新角色:
                    <el-select v-model="selectedRoleId" placeholder="请选择">
                        <el-option
                                v-for="item in roleList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <!--按钮区域-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRole">确 定</el-button>
              </span>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        name: "User",
        data() {
            const checkEmail = (rule, value, callback) => {
                const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
                if (!regEmail.test(value)) {
                    console.log(value);
                    callback(new Error('请输入合法的邮箱'));
                } else {
                    return callback();
                }
            };
            const checkMobile = (rule, value, callback) => {
                const regMobile = /^1[3456789]\d{9}$/;
                if (!regMobile.test(value)) {
                    callback(new Error('请输入合法的11位电话号码'));
                } else {
                    return callback();
                }
            };
            return {
                queryInfo: {
                    query: '',
                    pageSize: 10,
                    pageIndex: 1
                },
                tableData: [{
                    id: 1,
                    username: '兰州',
                    email: '18779177562@163.com',
                    mobile: '18779177562',
                    roles: '超级管理员',
                    status: true
                }],
                total: 100,
                /*控制添加对话框的显示和隐藏*/
                addDialogVisible: false,
                /*控制修改对话框的显示和隐藏*/
                editDialogVisible: false,
                form: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: '',
                },
                editForm: {
                    id: '',
                    username: '',
                    email: '',
                    mobile: '',
                },
                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '请输入电话号码', trigger: 'blur'},
                        {validator: checkMobile, trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '请输入邮箱地址', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ],
                },
                // 控制角色分配
                setRoleDialogVisible: false,
                userInfo: {},
                roleList: [
                    {
                        id: 1,
                        name: '人民教师',
                        descpt: '我是个讲师'
                    },
                    {
                        id: 2,
                        name: '放牛娃',
                        descpt: '放牛的娃娃'
                    }
                ],
                // 已经选择的角色ID 值
                selectedRoleId: ''
            }
        },
        created() {
            // this.getUsers();
        },
        methods: {
            // 异步请求用户数据
            async getUsers() {
                const {data: res} = await this.$http.post('users', {param: this.queryInfo});
                if (res.code + '' !== '200') {
                    this.$message.error('获取用户数据失败');
                } else {
                    // TODO 赋值数据, 并且分页数据绑定
                }
            },
            changeStatus(row) {
                // TODO 这个是修改后的状态, 需要同步到数据库
                console.log(row);
            },
            // 监听pageSize 改变
            handleSizeChange(newSize) {
                console.log(newSize);
                this.queryInfo.pageSize = newSize;
            },
            // 页码值改变的事件
            handleCurrentChange(newPage) {
                console.log(newPage);
                this.queryInfo.pageIndex = newPage;
            },
            // 关闭时获取表单引用调用resetFields 清空表单数据
            closeForm() {
                this.$refs.formRef.resetFields();
            },
            // 关闭时修改表单引用调用resetFields 清空表单数据
            closeEditForm() {
                this.$refs.editFormRef.resetFields();
            },
            // 添加数据
            addUser() {
                this.$refs.formRef.validate(valid => {
                    if (!valid) {
                        return;
                    }
                    // TODO 然后发起真正的网络请求添加数据
                    this.$message.success('添加成功');
                    const user = Object.assign({id: 10, status: true, roles: '普通数据'}, this.form);
                    this.tableData.push(user);
                    this.addDialogVisible = false;
                });
            },
            // 展示编辑用户对话框
            showEdit(row) {
                console.log(row);
                this.editForm = row;
                // TODO row.id 获取数据库数据作为回显, 防止前台数据被人修改
                this.editDialogVisible = true;
            },
            // 修改用户数据
            updateUser() {
                this.$refs.editFormRef.validate(valid => {
                    if (!valid) {
                        return;
                    }
                    // TODO 然后发起真正的网络请求添加数据
                    this.$message.success('添加成功');
                    this.getUsers();
                    this.editDialogVisible = false;
                });
            },
            // 删除数据
            async deleteUser(id) {
                const confirm = await this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                console.log(confirm); // confirm || cancel
                if (confirm === 'confirm') {
                    this.$message.success("已确认删除");
                    this.getUsers();

                    /*const {data: res} = await this.$http.post('users', {id: id});
                    if (res.code + '' === '200') {
                        this.$message.success("已确认删除");
                        this.getUsers();
                    } else {
                        return this.$message.error("删除失败, 请稍后重试");
                    }*/
                } else {
                    return this.$message.info("已取消删除");
                }
            },
            // 显示分配角色对话框
            showSetRole(userInfo) {
                // 展示对话框前获取所有角色列表
                // TODO 配置 this.roleList 和 this.selectedRoleId
                this.selectedRoleId = 1;
                this.userInfo = userInfo;
                this.setRoleDialogVisible = true;
            },
            // 分配角色
            setRole() {
                if(!this.selectedRoleId){
                    return this.$message.error('请选择要分配的角色');
                }
                // TODO 发请求修改我们的角色数据

                this.$message.success('修改成功');
                this.setRoleDialogVisible = false;
            },
            // 关闭分配角色对话框
            closeSetRoleForm() {
                this.selectedRoleId = '';
                this.userInfo = [];
            }
        }

    }
</script>

<style lang="less" scoped>


</style>
